package com.somnus.androidkotlindemo.activity

import android.content.Context
import android.content.Intent
import android.nfc.Tag
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.somnus.androidkotlindemo.R
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread

class CoroutinesActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coroutines)

//        Log.d(TAG, "kt Start")
//
//        //start a coroutine
//        launch {
//            delay(1000)
//            Log.d(TAG, "Hello , ")
//        }
//        //runBlocking{}会启动协程并等待协程执行完成
//        runBlocking {
//            delay(2000)
//            Log.d(TAG, "Run Blocking")
//        }
//
//
//
//        Thread.sleep(2000)
//        Log.d(TAG, "kt Stop")


//        createThreads()
//        createCoroutines()
        createAsyncCoroutines()
    }

    fun createAsyncCoroutines() {
        thread(start = true) {
            val deferrd = (1..1000).map { n ->
                //Async：从协程中返回来一个值
                async {
                    delay(1000)
                    Log.d(TAG,"$n")
                    n
                }
            }

//            500500
            runBlocking {
                //注：await()不能在协程之外使用，因为它需要挂起直到计算完成，
                // 并且只有协程能过在非阻塞的方式挂起。现在输出结果是1784293664，
                // 因为所有协程都执行完毕了，运行结果如下：
                val sum = deferrd.sumBy { it.await() }
                Log.d(TAG, "sum : $sum")
            }
        }
    }

    fun createCoroutines() {
        thread(start = true) {
            val c = AtomicInteger()
            for (i in 1..1_000) {
                launch {
                    c.addAndGet(i)
                }
            }
            Log.d(TAG, "${c.get()},conroutines")
        }
    }

    fun createThreads() {
        thread(start = true) {
            val c = AtomicInteger()
            for (i in 1..1_000) {
                thread(start = true) {
                    c.addAndGet(i)
                }
            }
            Log.d(TAG, "${c.get()},threads")
        }

    }

    companion object {
        private final val TAG: String = this.javaClass.simpleName

        fun startCoroutinesActivityActivity(context: Context) {

            val mIntent = Intent()
            mIntent.setClass(context, CoroutinesActivity::class.java)
            context.startActivity(mIntent)
        }
    }
}
